package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.behavior.service.mq.impl.ApUserOperationsServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author XHui
 * @Since 2024/2/22 15:26
 * @Version 1.0
 */
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Resource
    private ApBehaviorEntryService apBehaviorEntryService;

    @Resource
    private ApUserOperationsServiceImpl apUserOperationsService;

    // 通过Resource注解注入mongoTemplate
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        // 1. 获取当前登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();

        // 2. 查询当前用户的行为实体
        ApBehaviorEntry apBehaviorEntryByRefId = null;
        if (user != null) {
            apBehaviorEntryByRefId = apBehaviorEntryService
            .findByUserIdOrEquipmentId(user.getId(), null);
        } else {
            apBehaviorEntryByRefId = apBehaviorEntryService
                    .findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        }
        if(apBehaviorEntryByRefId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "未找到用户行为实体根据用户ID或者设备ID");
        }
        String entryId = apBehaviorEntryByRefId.getId();

        // 3. 查询用户是否是首次阅读当前文章 by  entryId + articleId
        Query query = Query.query(
                Criteria.where("entryId").is(entryId)
                        .and("articleId").is(dto.getArticleId())
        );
        ApReadBehavior readBehaviorDB = mongoTemplate.findOne(query, ApReadBehavior.class);

        // 4. 判断是否是首次阅读
        ApReadBehavior apReadBehavior = new ApReadBehavior();
        if(readBehaviorDB == null) {
            // 4.1 如果是首次阅读，则新增阅读记录
            apReadBehavior.setEntryId(entryId);
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount((short) 1);
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.insert(apReadBehavior);
        }  else {// 4.2 如果不是首次阅读，则更新阅读记录
            int count = readBehaviorDB.getCount() + (short) 1;
            readBehaviorDB.setCount((short) count);
            readBehaviorDB.setUpdatedTime(new Date());
            apReadBehavior =  readBehaviorDB; // 返回已存储阅读行为
            mongoTemplate.save(readBehaviorDB);
        }

        NewBehaviorDTO newBehaviorDTO = new NewBehaviorDTO();
        newBehaviorDTO.setAdd(1);
        newBehaviorDTO.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        newBehaviorDTO.setArticleId(dto.getArticleId());
        apUserOperationsService.sendUserOperationsToRabbitMQ(newBehaviorDTO);

        return ResponseResult.okResult(apReadBehavior);
    }
}
